package com.codebox.knowledge.xunfei;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.codebox.common.base.BaseActivity;
import com.codebox.common.common.RouterPath;
import com.codebox.common.util.LogUtils;
import com.codebox.common.util.ToastUtils;
import com.codebox.knowledge.R;
import com.codebox.knowledge.databinding.ActivitySpeechBinding;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * @author Able
 * @date 2019/1/2
 */
@Route(path = RouterPath.KnowledgeRouterPath.PATH_SPEECH)
public class SpeechActivity extends BaseActivity<ActivitySpeechBinding> {

    // 语音听写UI
    private RecognizerDialog mIatDialog;
    // 用HashMap存储听写结果
    private HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_speech);

        SpeechUtility.createUtility(this, SpeechConstant.APPID + "=5b59763b");

        initView();
        initSpeechDialog();
        initListener();
    }

    private void initView() {
        setTitle("语言识别");
        setNavigationIcon(R.drawable.ic_back);
    }

    private void initListener() {
        mBinding.btnStart.setOnClickListener(v -> startSpeech());
    }

    private void initSpeechDialog() {
        mIatDialog = new RecognizerDialog(this, mInitListener);
        //引擎
        mIatDialog.setParameter(SpeechConstant.DOMAIN, "iat");
        //语言
        mIatDialog.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        //方言（普通话）
        mIatDialog.setParameter(SpeechConstant.ACCENT, "mandarin");
        //不显示标点
        mIatDialog.setParameter(SpeechConstant.ASR_PTT, "0");
    }

    private void startSpeech() {
        mIatDialog.setListener(new MyRecognizerDialogListener());
        mIatDialog.show();
        // 隐藏提示文字
        TextView txt = (TextView) mIatDialog.getWindow().getDecorView().findViewWithTag("textlink");
        txt.setText("");
        txt.setClickable(false);
        Toast.makeText(SpeechActivity.this, "请开始说话...", Toast.LENGTH_SHORT).show();
    }

    /**
     * 初始化监听器。
     */
    public InitListener mInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
            LogUtils.d("SpeechRecognizer init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                Toast.makeText(SpeechActivity.this, "初始化失败，错误码：" + code, Toast.LENGTH_SHORT).show();
            }
        }
    };

    class MyRecognizerDialogListener implements RecognizerDialogListener {
        private int position;

        public MyRecognizerDialogListener() {
        }

        public MyRecognizerDialogListener(int position) {
            this.position = position;
        }

        /**
         * @param results
         * @param isLast  是否说完了
         */
        @Override
        public void onResult(RecognizerResult results, boolean isLast) {
            String result = results.getResultString(); //未解析的
            LogUtils.i(" 未解析的 ==:" + result);
            String text = JsonParser.parseIatResult(result);//解析后的
            LogUtils.i(" 解析后的 ==:" + text);
            String sn = null;
            // 读取json结果中的 sn字段
            try {
                JSONObject resultJson = new JSONObject(results.getResultString());
                sn = resultJson.optString("sn");
            } catch (JSONException e) {
                e.printStackTrace();
            }

            mIatResults.put(sn, text);//没有得到一句，添加到

            StringBuffer resultBuffer = new StringBuffer();
            for (String key : mIatResults.keySet()) {
                resultBuffer.append(mIatResults.get(key));
            }

            if (isLast) {
                String data = resultBuffer.toString();
//                if (RegexUtils.isPhone(data)) {
//                    // 给手机号插入空格
//                    StringBuffer buffer = new StringBuffer();
//                    buffer.append(data);
//                    buffer.insert(3, " ");
//                    buffer.insert(8, " ");
//                    mPackageData.get(position).setReceivePhone(buffer.toString());
//                    mPackageAdapter.notifyItemChanged(position);
//
//                    speechError = 0;
//                } else {
//                    Toast.makeText(ScanActivity.this, "请录入正确的手机号", Toast.LENGTH_SHORT).show();
//                    speechError++;
//                    if (speechError < 3) {
//                        startSpeech(position);
//                    } else {
//                        gotoInputPhone(position);
//                    }
//                }
                ToastUtils.showSuccess(data);
            }
        }

        @Override
        public void onError(SpeechError speechError) {

        }
    }
}
